import {Component } from '@angular/core';
import {ApesField} from './apes-field';
import {backField} from '../../../../utils/utils';
import {ApiService} from '@core/services/http/api.service';
import {Events} from '@core/services/events/Events';
import {ExpressionService} from '@core/services/expression/ExpressionService';
import {SubjectService} from '@core/services/events/subject.service';
import {Subject} from 'rxjs';
import { toNumber } from '@shared/apes/core/util/convert';


@Component({
  selector: 'formly-field-select-enumeration',
  template: `
    <ng-select
        [items]="itemsData"
        [placeholder]="to.placeholder"
        [searchable]="false"
        [multiple]="multiple"
        [loading]="contractLoading"
        [typeahead]="contractinput$"
        (change)="backData()"
        (scrollToEnd)="fetchMore()"
        [formlyAttributes]="field"
        [formControl]="formControl"
        [disabled]="to.disabled">
        <ng-template ng-label-tmp let-item="item">
            {{formatter(item, getValueFormatter())}}
        </ng-template>
        <ng-template ng-option-tmp let-item="item">
            {{formatter(item, getDownFormatter())}}
        </ng-template>
    </ng-select>
  `
})
export class FormlyFieldSelectEnumeration extends ApesField {

  private _value: any;
  private _current = 0;
  private _pages = 0;
  private _size = 20;
  private api = 'cm.enumeration.findByType';
  itemsData: any[];
  multiple = false;
  contractLoading = false;
  contractinput$ = new Subject<string>();
  _searchText: string;
  placeholder: string;

  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit() {
    this._searchText = this.to.typeId;
    this.multiple = this.to.multiple === 'true' || false;
    this._size = this.to.size ? toNumber(this.to.size) : this._size;
    this.getItemData();
    this.addDefalutPlaceholder('请选择');
  }


  getDownFormatter(): string {
    return this.to.downFormatter || 'value.description';
  }

  getValueFormatter(): string {
    return this.to.valueFormatter || 'value.description';
  }


  backData() {
    const context = this.to.context || {};
    backField(this, context);
  }

  getItemData() {
    if ( !this._searchText ) return false;
    const data = {key: this._searchText, page: this._current, size: this._size};
    this.apiService.post(this.api, data).subscribe(item => {
      this.contractLoading = false;
      if (item.page === 0) {
        this.itemsData = [];
      }
      this.itemsData = this.itemsData.concat(item.content);
      this._current = item.page + 1;
      this._pages = item.pages;
    });
  }


  fetchMore() {
    this.contractLoading = true;
    // using timeout here to simulate backend API delay
    if (this._current === this._pages || this._searchText === '') {
      this.contractLoading = false;
      return;
    }

    this.getItemData();

  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      context: this.formState,
      model: this.formState.model,
      value: value
    });
  }
}
